package com.cy.train.gateway.config;

import cn.hutool.core.util.ObjectUtil;
import com.cy.train.gateway.util.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Description:
 * @Date: 2024/2/27 11:15
 * @Author: cyzhang
 */
@Component
public class MemberLoginFilter implements GlobalFilter, Ordered {
    private static final Logger LOG = LoggerFactory.getLogger(MemberLoginFilter.class);
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String path = exchange.getRequest().getURI().getPath();

        if(path.contains("/admin")
                || path.contains("/redis")
                || path.contains("/hello")
                || path.contains("/send-code")
                || path.contains("/login")) {
            LOG.info("不需要登录验证：{}", path);
            return chain.filter(exchange);
        } else {
            LOG.info("需要登录验证：{}", path);
        }

        String token = exchange.getRequest().getHeaders().getFirst("token");
        LOG.info("登录验证开始，token：{}", token);

        if(ObjectUtil.isNull(token)) {
            LOG.info("token为空，请求被拦截");
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }

        boolean validate = JwtUtil.validate(token);
        if(validate) {
            LOG.info("token有效，请求放行");
            return chain.filter(exchange);
        } else {
            LOG.info("token无效，请求拦截");
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
